package io.laputa.offer.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.laputa.offer.entity.User;
import io.laputa.offer.service.UserService;
import io.laputa.offer.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author Qsh
 * @since 2024/9/14
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        log.info("username: {}", user.getUsername());
        log.info("password: {}", user.getPassword());
        Map<String, Object> res = new HashMap<>();
        try {
            User userDB = userService.login(user);
            //生成JWT令牌
            Map<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(userDB.getId()));
            payload.put("username", userDB.getUsername());
            String token = JWTUtil.getToken(payload);
            log.info("token: {}", token);
            res.put("state", true);
            res.put("msg", "认证成功");
            res.put("token", token);
        } catch (JWTVerificationException e) {
            res.put("state", false);
            res.put("msg", e.getMessage());
        }
        return res;
    }

    @PostMapping("/verify")
    public Map<String, Object> verify(@RequestHeader(required = false) String token) {
        Map<String, Object> res = new HashMap<>();
        if (!StringUtils.hasText(token)) return res;
        DecodedJWT decodedJWT = JWTUtil.getInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        res.put("state", true);
        res.put("msg", "请求成功");
        res.put("id", id);
        return res;
    }

    //退出登录 TODO

    //刷新token时间 TODO
}
